﻿using FluentAssertions;
using StackExchange.Redis;
using System;

namespace NewRetail.Application.Core
{
    public class RedisClient : IDisposable
    {
        private readonly ConnectionMultiplexer _con;
        public string ConnectionString { get; }

        public RedisClient(ConnectionMultiplexer con)
        {
            this._con = con ?? throw new ArgumentNullException(nameof(IConnectionMultiplexer));
        }

        static ConnectionMultiplexer __connect__(string con_str)
        {
            con_str.Should().NotBeNullOrEmpty();

            var res = ConnectionMultiplexer.Connect(con_str);
            //var i = 0;
            //while (!res.IsConnected)
            //{
            //    System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1));
            //    (++i).Should().BeLessThan(10, "无法链接redis，等待时间过长");
            //}

            return res;
        }

        public RedisClient(string connectionString) : this(__connect__(connectionString))
        {
            this.ConnectionString = connectionString;
            this.ConnectionString.Should().NotBeNullOrEmpty();
        }

        public ConnectionMultiplexer Connection => this._con;

        public void Dispose()
        {
            this._con?.Dispose();
        }
    }
}
